// 订单历史功能
document.addEventListener('DOMContentLoaded', function() {
    loadAllOrders();
});

// 加载所有订单
function loadAllOrders() {
    const ordersList = document.getElementById('allOrdersList');
    if (!ordersList) return;
    
    // 显示加载状态
    ordersList.innerHTML = `
        <div class="order-item" data-skeleton>
            <div class="order-info">
                <h5>加载中…</h5>
                <p>正在获取历史订单</p>
            </div>
            <span class="status-badge">···</span>
        </div>
    `;
    
    // 从后端接口获取订单历史
    apiService.getOrderHistory()
    .then(function(data) {
        console.log('订单历史数据:', data);
        updateAllOrdersList(data.orders || []);
    })
    .catch(function(error) {
        console.error('获取订单历史失败:', error);
        showAllOrdersError();
    });
}

// 更新所有订单列表
function updateAllOrdersList(orders) {
    const ordersList = document.getElementById('allOrdersList');
    if (!ordersList) return;
    
    if (orders.length === 0) {
        ordersList.innerHTML = `
            <div class="order-item">
                <div class="order-info">
                    <h5>暂无订单</h5>
                    <p>您还没有任何订单记录</p>
                </div>
                <span class="status-badge">-</span>
            </div>
        `;
        return;
    }
    
    // 按时间倒序排列
    orders.sort((a, b) => new Date(b.orderTime) - new Date(a.orderTime));
    
    ordersList.innerHTML = orders.map(order => `
        <div class="order-item" onclick="showOrderDetails('${order.orderNumber}')">
            <div class="order-info">
                <h5>订单 #${order.orderNumber}</h5>
                <p>${order.items.length}个商品 · ${formatOrderTime(order.orderTime)}</p>
                <div class="order-items-preview">
                    ${order.items.slice(0, 2).map(item => 
                        `${item.name} x${item.quantity}`
                    ).join(', ')}${order.items.length > 2 ? '...' : ''}
                </div>
            </div>
            <div class="order-right">
                <span class="order-total">¥${order.totalAmount.toFixed(2)}</span>
                <span class="status-badge ${order.status}">${getStatusText(order.status)}</span>
            </div>
        </div>
    `).join('');
}

// 显示所有订单错误
function showAllOrdersError() {
    const ordersList = document.getElementById('allOrdersList');
    if (!ordersList) return;
    
    ordersList.innerHTML = `
        <div class="order-item error">
            <div class="order-info">
                <h5>连接失败</h5>
                <p>无法获取订单数据</p>
            </div>
            <span class="status-badge error">错误</span>
        </div>
    `;
}

// 显示订单详情
function showOrderDetails(orderNumber) {
    // 从后端获取订单详情
    apiService.getOrderDetails(orderNumber)
    .then(function(order) {
        displayOrderDetails(order);
    })
    .catch(function(error) {
        console.error('获取订单详情失败:', error);
        alert('获取订单详情失败：' + error.message);
    });
}

// 显示订单详情模态框
function displayOrderDetails(order) {
    const itemsHtml = order.items.map(item => `
        <div class="order-detail-item">
            <div class="item-info">
                <span class="item-name">${item.name}</span>
                <span class="item-quantity">x${item.quantity}</span>
            </div>
            <span class="item-total">¥${item.total.toFixed(2)}</span>
        </div>
    `).join('');
    
    const modalHtml = `
        <div class="order-detail-modal" id="orderDetailModal">
            <div class="modal-content">
                <div class="modal-header">
                    <h3>订单详情 #${order.orderNumber}</h3>
                    <button class="close-btn" onclick="closeOrderDetails()">×</button>
                </div>
                <div class="modal-body">
                    <div class="order-info-section">
                        <div class="info-row">
                            <span class="label">订单时间：</span>
                            <span class="value">${formatOrderTime(order.orderTime)}</span>
                        </div>
                        <div class="info-row">
                            <span class="label">餐厅：</span>
                            <span class="value">${order.restaurant}</span>
                        </div>
                        <div class="info-row">
                            <span class="label">客户：</span>
                            <span class="value">${order.customerName}</span>
                        </div>
                        <div class="info-row">
                            <span class="label">订单状态：</span>
                            <span class="value status-${order.status}">${getStatusText(order.status)}</span>
                        </div>
                    </div>
                    
                    <div class="order-items-section">
                        <h4>商品清单</h4>
                        <div class="order-items-list">
                            ${itemsHtml}
                        </div>
                    </div>
                    
                    <div class="order-total-section">
                        <div class="total-row">
                            <span class="label">总计：</span>
                            <span class="value total-amount">¥${order.totalAmount.toFixed(2)}</span>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" onclick="closeOrderDetails()">关闭</button>
                    ${order.status === 'pending' ? '<button class="btn btn-danger" onclick="cancelOrder(\'' + order.orderNumber + '\')">取消订单</button>' : ''}
                </div>
            </div>
        </div>
    `;
    
    // 移除已存在的模态框
    const existingModal = document.getElementById('orderDetailModal');
    if (existingModal) {
        existingModal.remove();
    }
    
    // 添加新模态框
    document.body.insertAdjacentHTML('beforeend', modalHtml);
    
    // 添加样式
    if (!document.getElementById('orderDetailStyles')) {
        const styles = `
            <style id="orderDetailStyles">
                .order-detail-modal {
                    position: fixed;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    background: rgba(0, 0, 0, 0.5);
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    z-index: 1000;
                }
                
                .modal-content {
                    background: white;
                    border-radius: 8px;
                    max-width: 500px;
                    width: 90%;
                    max-height: 80vh;
                    overflow-y: auto;
                }
                
                .modal-header {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    padding: 20px;
                    border-bottom: 1px solid #eee;
                }
                
                .close-btn {
                    background: none;
                    border: none;
                    font-size: 24px;
                    cursor: pointer;
                }
                
                .modal-body {
                    padding: 20px;
                }
                
                .order-info-section {
                    margin-bottom: 20px;
                }
                
                .info-row {
                    display: flex;
                    justify-content: space-between;
                    margin-bottom: 10px;
                }
                
                .label {
                    font-weight: bold;
                }
                
                .order-items-section h4 {
                    margin-bottom: 15px;
                }
                
                .order-detail-item {
                    display: flex;
                    justify-content: space-between;
                    padding: 10px 0;
                    border-bottom: 1px solid #f0f0f0;
                }
                
                .item-info {
                    display: flex;
                    flex-direction: column;
                }
                
                .item-quantity {
                    color: #666;
                    font-size: 14px;
                }
                
                .order-total-section {
                    margin-top: 20px;
                    padding-top: 20px;
                    border-top: 2px solid #eee;
                }
                
                .total-row {
                    display: flex;
                    justify-content: space-between;
                    font-size: 18px;
                    font-weight: bold;
                }
                
                .modal-footer {
                    padding: 20px;
                    border-top: 1px solid #eee;
                    display: flex;
                    justify-content: flex-end;
                    gap: 10px;
                }
                
                .btn {
                    padding: 8px 16px;
                    border: none;
                    border-radius: 4px;
                    cursor: pointer;
                }
                
                .btn-secondary {
                    background: #6c757d;
                    color: white;
                }
                
                .btn-danger {
                    background: #dc3545;
                    color: white;
                }
                
                .status-pending { color: #ffc107; }
                .status-preparing { color: #17a2b8; }
                .status-ready { color: #28a745; }
                .status-completed { color: #6c757d; }
                .status-cancelled { color: #dc3545; }
            </style>
        `;
        document.head.insertAdjacentHTML('beforeend', styles);
    }
}

// 关闭订单详情
function closeOrderDetails() {
    const modal = document.getElementById('orderDetailModal');
    if (modal) {
        modal.remove();
    }
}

// 取消订单
function cancelOrder(orderNumber) {
    if (!confirm('确定要取消这个订单吗？')) {
        return;
    }
    
    apiService.cancelOrder(orderNumber)
    .then(function(data) {
        alert('订单已取消');
        
        // 关闭模态框
        closeOrderDetails();
        
        // 刷新订单列表
        loadAllOrders();
    })
    .catch(function(error) {
        console.error('取消订单失败:', error);
        alert('取消订单失败：' + error.message);
    });
}

// 格式化订单时间
function formatOrderTime(timestamp) {
    const date = new Date(timestamp);
    const now = new Date();
    const diff = now - date;
    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);
    const days = Math.floor(diff / 86400000);
    
    if (minutes < 1) return '刚刚';
    if (minutes < 60) return `${minutes}分钟前`;
    if (hours < 24) return `${hours}小时前`;
    if (days < 7) return `${days}天前`;
    
    return date.toLocaleDateString('zh-CN');
}

// 获取状态文本
function getStatusText(status) {
    const statusMap = {
        'pending': '待处理',
        'preparing': '制作中',
        'ready': '待取餐',
        'completed': '已完成',
        'cancelled': '已取消'
    };
    return statusMap[status] || status;
}